#include "fxcc/core/audio/common/AudioImporter.h"

AudioMetaCacheFile AudioImporter::m_AudioMetaData;

std::string AudioImporter::m_AudioMetaPath = ".metamap/audio.metamap";

std::string AudioImporter::m_AudioPath = "Audio";

bool AudioImporter::ImportFile(const fxcc::File& file)
{
	switch (file.m_FileType)
	{
	case fxcc::FileType::_Ogg_:
	case fxcc::FileType::_Wav_:
	case fxcc::FileType::_MP3_:
		return ImportAudioFile(file);
	default:
		return false;
	}


	return true;
}

bool AudioImporter::ImportAudioFile(const fxcc::File& file)
{
	std::string path = file.m_RelativePath;

	auto& m_MetaCache = m_AudioMetaData.m_AudioMetaCaches[path];

	MetaMapIndex metaMapIndex;
	metaMapIndex.SetNativePath(path);

	std::string fileName = file.m_FileName;

	fs::path _dir = m_LibraryPath / fs::path("Audio");

	metaMapIndex.SetAudio(_dir.string(), path, 0);
	metaMapIndex.SetName(fileName);

	m_MetaCache.m_Audios.push_back(metaMapIndex);

	TransAudioFileToOgg(metaMapIndex.m_NativeFile, metaMapIndex.m_TargetFilePath);

	return fs::exists(metaMapIndex.m_TargetFilePath);
}

bool AudioImporter::TransAudioFileToOgg(const std::string& source, const std::string& target)
{
	fxcc::Base::CreateParentDirs(target);

	kainjow::mustache::mustache m1 = std::string(
		R"(ffmpeg -y  -i "{{{source}}}" -vn -c:a libvorbis "{{{targetPath}}}")"
	);
	kainjow::mustache::data d1;

	d1.set("source", source);
	d1.set("targetPath", target);

	std::string cmdText = m1.render(d1);
	return sysx::System::ExecuteCmd(cmdText);

}

bool AudioImporter::Availed(const fxcc::File& file)
{
	switch (file.m_FileType)
	{
	case fxcc::FileType::_Ogg_:
	case fxcc::FileType::_Wav_:
	case fxcc::FileType::_MP3_:
		return true;
	default:
		return false;
	}
}

bool AudioImporter::SaveCache()
{
	fxcc::yml::Serializer serializer;
	FXCC_FAILED(serializer.EncodePath<AudioMetaCacheFile>(m_AudioMetaPath, m_AudioMetaData));
	return true;
}

bool AudioImporter::LoadCache()
{
	fxcc::yml::Serializer serializer;
	FXCC_FAILED(serializer.DecodePath<AudioMetaCacheFile>(m_AudioMetaPath, m_AudioMetaData));
	return true;
}